import advListV from "../view/advList.ejs";
import {getAdvList, postAdv, putAdv} from "../api/adv";
import AdvTableV from "../components/AdvTable.ejs";
const advTypeEnum = {
	1:"轮播图广告",
	2:"轮播图底部广告",
	3:"热门回收",
	4:"优品精选"
}
let preImg;
let advList = [];
let info={};
const getAdvListAsync = async function(pageNo=1){
	const data = await getAdvList(pageNo,2,document.querySelector("#keyword").value);
	advList = data.advList;
	document.querySelector("#advTable").innerHTML = AdvTableV({
		...data,
		advTypeEnum
	});
	document.querySelector("#pageUl").onclick = function(e){
		const page = e.target.dataset.page;
		if(page){
			getAdvListAsync(page);
		}
	}
}
export default ()=>{
	return async (req, res) => {
		res.render(advListV());
		preImg = document.querySelector("#preImg");
		getAdvListAsync();
		document.querySelector(".input-group-append").onclick =getAdvListAsync.bind(this,1);
		// 为添加广告按钮增加事件
		document.querySelector("#addAdvBtn").onclick = function(){
			document.advForm.reset();// 清空表单
			document.querySelector(".modal-title").innerText = "添加广告";
			preImg.style.display = "none";
			$("#modal-default").modal("show");// 显示弹出层
		}
		// 提交表单按钮
		document.querySelector("#adv-save").onclick = async function(){
			const formdata = new FormData(document.advForm);// 创建一个FormData实例
			let response;
			if(document.querySelector(".modal-title").innerText === "添加广告"){
				response = await postAdv(formdata);// 添加
			}else{
				response = await putAdv(info._id,formdata);
			}
			toastr.success(response.msg);
			$("#modal-default").modal("hide");
			getAdvListAsync();

		}
		// 选中图片事件
		document.querySelector("#advPic").onchange = function(e){
			const fileReader = new FileReader();
			fileReader.readAsDataURL(e.target.files[0]);
			fileReader.onload = function(event){
				// console.log(event.currentTarget.result);
				preImg.style.display = "block";
				preImg.src = event.currentTarget.result;
			}
		}
		document.querySelector("#advTable").onclick = function(e){
			if(e.target.classList.contains("btn-success")){
				document.querySelector(".modal-title").innerText = "修改广告";
				info = advList.find(v=>v._id === e.target.dataset.id);
				document.advForm.advTitle.value = info.advTitle;
				document.advForm.advHref.value = info.advHref;
				document.advForm.advType.value = info.advType;
				document.advForm.advOrder.value = info.advOrder;
				preImg.src = "/api/"+info.advPic;
				preImg.style.display = "block";
				$("#modal-default").modal("show");// 显示弹出层

			}
		}


	}
}